//
//  ChainAccountSetVC.m
//  Chain
//
//  Created by zhaosh on 2018/4/12.
//  Copyright © 2018年 zhaosh. All rights reserved.
//

#import "ChainAccountSetController.h"
#import "ChainAccountSetItem.h"
#import "ChainAccountSetCell.h"
#import "ChainCacheTool.h"
#import "ChainLoginVC.h"

@interface ChainAccountSetController()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) UITableView *myTableView;
@end

@implementation ChainAccountSetController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(CGFLOAT_MIN * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        UIViewController *vc = [self.navigationController.viewControllers lastObject];
        if (vc.fd_prefersNavigationBarHidden) {
            [self.navigationController setNavigationBarHidden:YES animated:NO];
        } else {
            [self.navigationController setNavigationBarHidden:NO animated:NO];
        }
    });

    NSString *cacheSize = [ChainCacheTool getCacheSize];
    for (ChainAccountSetItem *item in self.dataArray) {
        if ([item.tileName isEqualToString:@"系统缓存"]) {
            item.valueNum = cacheSize;
            break;
        }
    }
    [self.myTableView reloadData];
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}

-(void)viewDidLoad{
    [super viewDidLoad];
    [self setHeadView:self.view withLeftBtnText:@"chainBack" withHeadLable:@"系统设置" withRightBntText:@""];
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app版本
    NSString *app_Version = [NSString stringWithFormat:@"V%@",[infoDictionary objectForKey:@"CFBundleShortVersionString"]];
 
    NSArray *tempArr=[NSArray arrayWithObjects:@{@"tileName": @"系统缓存"},@{@"tileName" : @"系统版本",@"valueNum":app_Version},nil];
    for (NSDictionary *dic in tempArr) {
        ChainAccountSetItem *item =[ChainAccountSetItem yy_modelWithDictionary:dic];
        [self.dataArray addObject:item];
    }
    [self addTableView];
}

- (void)addTableView {
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,kTopHeight, ScreenWidth, ScreenHeight-kTopHeight) style:UITableViewStylePlain];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTableView.backgroundColor = [UIColor whiteColor];
    self.myTableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.myTableView];
    self.myTableView.scrollEnabled =NO;
    
    UIView *tableFooterView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height-180)];
    tableFooterView.backgroundColor = [UIColor whiteColor];
    
    UIButton *sureButton=[[UIButton alloc] initWithFrame:CGRectMake(30, tableFooterView.height-100, self.view.width-60, 50)];
    [sureButton setBackgroundColor:[UIColor colorWithHexString:@"#ce0d0d"]];
    sureButton.titleLabel.textColor=[UIColor whiteColor];
    sureButton.titleLabel.font=[UIFont boldSystemFontOfSize:16];
    [sureButton setTitle:@"退出登录" forState:UIControlStateNormal];
    [sureButton addTarget:self action:@selector(doTouchLoginOutBtn:) forControlEvents:UIControlEventTouchUpInside];
    sureButton.layer.masksToBounds = YES;
    sureButton.layer.cornerRadius=5;
    [tableFooterView addSubview:sureButton];
    
    [self.myTableView setTableFooterView:tableFooterView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"AccountCell";
    ChainAccountSetCell *cell = (ChainAccountSetCell*)[tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil){
        cell = [[ChainAccountSetCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.item=self.dataArray[indexPath.row];
    if (indexPath.row==0) {
         cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }else{
         cell.accessoryType = UITableViewCellAccessoryNone;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return  65;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
     ChainAccountSetItem *item = self.dataArray[indexPath.row];
    if([item.tileName isEqualToString:@"系统缓存"]){
        NSString *cacheNum = [[NSString stringWithFormat:@"%@",item.valueNum] stringByReplacingOccurrencesOfString:@"M" withString:@""];
        if ([cacheNum doubleValue] <= 0) {
            [self showRemindWithMessage:@"已经清空所有缓存数据"];
            return;
        }else{
            [self clearCache];
        }
    }
}

-(void)doTouchLoginOutBtn:(UIButton *)btn{
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"确定要退出吗?" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击了按钮1，进入按钮1的事件");
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
      
        NSString *requestUrl=[NSString stringWithFormat:@"%@%@",BASE_URL,LoginOut_Url];
        __weak typeof(self) weakSelf=self;
        [[ChainNetAPIClient sharedJsonClient]postRequestJsonDataWithPath:requestUrl withParams:nil withHeader:nil andBlock:^(id data, NSError *error) {
            NSDictionary *info = [NSDictionary dictionaryWithDictionary:data];
            if (error) {
                NSString *message=[info objectForKey:@"message"];
                [MBProgressHUD  showMessage:message ToView:nil RemainTime:0.8];
            }else{
                NSString *success=[NSString stringWithFormat:@"%@",[info objectForKey:@"status"]];
                if ([success isEqualToString:@"OK"]) {
                    [weakSelf.navigationController popViewControllerAnimated:NO];
                    
                    [weakSelf removeAccountCache];
                    
                    ChainLoginVC *vc=[[ChainLoginVC alloc] init];
                    [weakSelf.parentViewController.navigationController pushViewController:vc animated:NO];
                }
            }
        }];
    }];
    [actionSheet addAction:action1];
    [actionSheet addAction:action2];
    //相当于之前的[actionSheet show];
    [self presentViewController:actionSheet animated:YES completion:nil];
}

-(void)removeAccountCache{
    NSUserDefaults *userDefatluts = [NSUserDefaults standardUserDefaults];
    [userDefatluts removeObjectForKey:@"sessionId"];
    [userDefatluts removeObjectForKey:@"userId"];
    [userDefatluts removeObjectForKey:@"nickName"];
    [userDefatluts synchronize];
}

//清楚缓存
-(void)clearCache{
    NSString *cacheSize = [ChainCacheTool clearCache];
    ChainAccountSetItem *item = self.dataArray[0];
    item.valueNum = cacheSize;
    [self.myTableView reloadData];
}

- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
